const fs = require("fs")
const { prompt } = require("enquirer")
const articlesConfig = require("../articles/config.json")

let categoryType = ""

const noteTemplate = `<h1 style="text-align:center;opacity:0.8;">标题</h1>

<div style="text-align:right;margin-right:10px;font-size:16px;" >${new Date()
  .toLocaleDateString()
  .replaceAll("/", "-")} 晴</div>

<my-text-block color="var(--themeColor)" title="Note">

<my-p></my-p>

</my-text-block>

<my-text-block color="var(--themeColor)" title="Music">
<my-music id="1995174272"></my-music>
</my-text-block>`

async function selectArticleType() {
  const { articleType } = await prompt({
    type: "select",
    name: "articleType",
    message: "Select Article Type",
    choices: ["note", "none"],
  })
  return articleType
}

async function main() {
  const articleType = await selectArticleType()
  categoryType = articleType === "note" ? "随记" : ""
  const settingContent = `<blog-title></blog-title>
<blog-intro></blog-intro>
<blog-img></blog-img>
<blog-createTime>${new Date().toLocaleString()}</blog-createTime>
<blog-updateTime></blog-updateTime>
<blog-tag></blog-tag>
<blog-category>${categoryType}</blog-category>
|||

`
  const pageSize = 6
  const moveFileId = articlesConfig.articlesCount - pageSize + 1

  await fs.rename(`articles/first/${moveFileId}.md`, `articles/end/${moveFileId}.md`, err => {
    if (err) {
      console.error("Failed to move the file:", err)
    } else {
      console.log("File moved successfully!")
    }
  })

  await fs.writeFile(
    `articles/first/${articlesConfig.articlesCount + 1}.md`,
    articleType === "note" ? settingContent + noteTemplate : settingContent,
    () => {
      console.log(`new article ${articlesConfig.articlesCount}.md is created`)
    }
  )

  articlesConfig.articlesCount = articlesConfig.articlesCount + 1
  await fs.writeFile("articles/config.json", JSON.stringify(articlesConfig, null, 2), err => {
    if (err) {
      console.log("An error has occurred ", err)
      return
    }
    console.log("written successfully")
  })
}

main()
